import ToolWindow from "@/tool/ToolWindow.js";
import ToolLoadJs from "@/tool/ToolLoadJs.js";

let videoType = 0;
let oWebControl;
let pubKey;
let dom;

export function resize() {
	if (oWebControl && dom) {
		oWebControl.JS_Resize(dom.offsetWidth, dom.offsetHeight);
	}
}

// ToolWindow.addWinResize(resize)

let domLeft = undefined;
let domTop = undefined;
let domShow = true;

setInterval(() => {
	if (oWebControl && dom) {
		let rect = dom.getBoundingClientRect();
		if (rect.left !== domLeft || rect.top != domTop) {
			domLeft = rect.left;
			domTop = rect.top;
			resize();
		}
		// if (!(rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement
		// 			.clientHeight) &&
		// 		rect.right <= (window.innerWidth || document.documentElement.clientWidth))) {
		// 	closeVideo();
		// }
		if (rect.width === 0 || rect.height === 0) {
			if (domShow) {
				oWebControl.JS_HideWnd();
				domShow = false;
			}
		} else {
			if (!domShow) {
				oWebControl.JS_ShowWnd();
				domShow = true;
			}
		}
		if (!ToolWindow.exist(dom)) {
			closeVideo();
		}
	}
}, 300);

ToolWindow.addWinRefresh(() => {
	closeVideo()
})

// 多路监控摄像头播放初始化插件
async function initPlugin(cameraIndexCode = "6d97475c2fce4457a453f459e0c966d5", domId = "playWnd", layout = "1x1") {
	closeVideo();
	console.log("----- 开始初始化海康插件 -----");
	if (!oWebControl) {
		console.log("----- 开始加载海康插件库 -----");
		await ToolLoadJs.loadJSList([
			"http://115.29.192.252:39000/cdn/haikang/jquery-3.2.1.min.js",
			"http://115.29.192.252:39000/cdn/haikang/jsencrypt.min.js",
			"http://115.29.192.252:39000/cdn/haikang/jsWebControl-1.0.0.min.js"
		])
	}
	setTimeout(() => {
		dom = document.getElementById(domId);
		oWebControl = new WebControl({
			szPluginContainer: domId,
			iServicePortStart: 15900,
			iServicePortEnd: 15900,
			szClassId: "23BF3B0A-2C56-4D97-9C03-0CB103AA8F11", // 用于IE10使用ActiveX的clsid
			cbConnectSuccess(res) {
				console.log('----- 视频插件开始初始化成功 -----');
				oWebControl.JS_StartService("window", {
						dllPath: "./VideoPluginConnect.dll",
					})
					.then(function() {
						oWebControl
							.JS_CreateWnd(domId, dom.clientWidth, dom.clientHeight)
							.then(function() {
								getPubKey(function() {
									oWebControl
										.JS_RequestInterface({
											funcName: "init",
											argument: JSON.stringify({
												appkey: "23991440",
												secret: setEncrypt(
													"G9MvIH2NnYQ4hLJ1eG6p"
												),
												ip: "117.158.156.150",
												playMode: videoType, // 0 预览 , 1 回放
												port: 801,
												snapDir: "D:\\SnapDir",
												videoDir: "D:\\VideoDir",
												layout: layout,
												enableHTTPS: 0,
												encryptedFields: "secret",
												showToolbar: 1, //是否显示工具栏，0-不显示，非0-显示
												showSmart: 1, //是否显示智能信息（如配置移动侦测后画面上的线框），0-不显示，非0-显示
												buttonIDs: "0,16,256,257,258,259,260,512,513,514,515,516,517,768,769", //自定义工具条按钮
											}),
										})
										.then(function(oData) {
											let wndId = -1;
											if (videoType == 1) {
												let start = parseTime(
														new Date(),
														'{y}-{m}-{d}') +
													' 00:00:00'
												var startTimeStamp = new Date(
														start)
													.getTime(); //回放开始时间戳，必填
												var endTimeStamp = new Date()
													.getTime();
												oWebControl
													.JS_RequestInterface({
														funcName: "startPlayback",
														argument: JSON
															.stringify({
																cameraIndexCode, //监控点编号
																startTimeStamp: Math
																	.floor(
																		startTimeStamp /
																		1000
																	)
																	.toString(), //录像查询开始时间戳，单位：秒
																endTimeStamp: Math
																	.floor(
																		endTimeStamp /
																		1000
																	)
																	.toString(), //录像结束开始时间戳，单位：秒
																recordLocation: 1, //录像存储类型：0-中心存储，1-设备存储
																transMode: 1,
																gpuMode: 0,
																wndId: wndId, //可指定播放窗口
															})
													})
											} else {
												oWebControl
													.JS_RequestInterface({
														funcName: "startPreview",
														argument: JSON
															.stringify({
																cameraIndexCode,
																streamMode: 0,
																transMode: 1,
																gpuMode: 0,
																wndId: wndId,
															}),
													})
													.then(function(oData) {});
											}
										});
								});
							});
					});
			},
			cbConnectError: function(err) {
				WebControl.JS_WakeUp("VideoWebPlugin://");
				oWebControl = null;
				console.log("插件未启动，正在尝试启动，请稍候...");
				console.log('链接websocket异常：', err)
				console.log(
					'检测到插件未安装，请下载安装刷新后重试！( "http://gw.zzfmhb.com/download/VideoWebPlugin.exe")'
				)
			},
			cbConnectClose: function() {
				oWebControl = null;
			},
		});
	}, 1);
}

function closeVideo() {
	console.log("----- 关闭海康插件 -----");
	if (oWebControl != null) {
		try {
			oWebControl.JS_HideWnd(); // 先让窗口隐藏，规避插件窗口滞后于浏览器消失问题
			oWebControl.JS_Disconnect().then(function() {
					console.log('视频链接断开成功！')
				},
				function() {
					console.log('视频链接断开异常......')
				});
		} catch (e) {
			console.error('视频关闭异常:', e);
		} finally {
			oWebControl = null;
			console.log("----- 关闭海康插件-成功 -----");
		}
	}
}

// 获取公钥
function getPubKey(callback) {
	oWebControl.JS_RequestInterface({
			funcName: "getRSAPubKey",
			argument: JSON.stringify({
				keyLength: 1024,
			}),
		})
		.then(function(oData) {
			// console.log(oData)
			if (oData.responseMsg.data) {
				pubKey = oData.responseMsg.data;
				callback();
			}
		});
}

// RSA加密
function setEncrypt(value) {
	var encrypt = new JSEncrypt();
	encrypt.setPublicKey(pubKey);
	return encrypt.encrypt(value);
}

export default {
	initPlugin,
	closeVideo,
	resize
}
